package com.healthMedical.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.healthMedical.constant.RedisConstant;
import com.healthMedical.entity.PageResult;
import com.healthMedical.entity.QueryPageBean;
import com.healthMedical.mapper.setMealMapper;
import com.healthMedical.pojo.Setmeal;
import com.healthMedical.service.setMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.healthMedical.utils.QiniuUtils.deleteFileFromQiniu;

@Service(interfaceClass = setMealService.class)
@Transactional
public class setMealServiceImpl implements setMealService {
    @Resource
    private setMealMapper setMealMapper;
    @Autowired
    private JedisPool jedisPool;
    @Resource
    private FreeMarkerConfigurer configurer;
    @Value("${out_put_path}")
    //从属性文件中读取要生成的html对应的目录
    private String outPutPath;
    //新增
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //添加套餐
        setMealMapper.add(setmeal);
        //添加相关联的检查组
        if(checkgroupIds!=null && checkgroupIds.length>0 ){
            addCheckGroups(setmeal.getId(),checkgroupIds);
        }
        //保存图片名称
        String fileName = setmeal.getImg();
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,fileName);

        //当添加套餐后重新生成静态页面(套餐详情页面、套餐列表页面)
        //新增套餐后需要重新生成静态页面
        generateMobileStaticHtml();
    }

    private void generateMobileStaticHtml() {
        //准备模板文件中所需的数据
        List<Setmeal> setmealList = setMealMapper.getAll();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面（多个）
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("setmealList", setmealList);
        this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);
    }

    //生成套餐详情静态页面（多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        for (Setmeal setmeal : setmealList) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("setmeal", this.findById(setmeal.getId()));
            this.generateHtml("mobile_setmeal_detail.ftl",
                    "setmeal_detail_"+setmeal.getId()+".html",
                    dataMap);
        }
    }

    //生成静态页面
    //模板名称、文件名、对应的数据
    public void generateHtml(String teplateName,String htmlPageName,Map map){
        Configuration configuration = configurer.getConfiguration();
        Writer out=null;
        try {
            Template template= configuration.getTemplate(teplateName);
            //构造输出流
            out=new FileWriter("E:/项目"+outPutPath+"/"+htmlPageName);
            template.process(map,out);
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }



    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage=queryPageBean.getCurrentPage();
        Integer pageSize= queryPageBean.getPageSize();
        String queryString=queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);

        Page<Setmeal> setMeals=setMealMapper.findSetMealByCondition(queryString);
        Long total=setMeals.getTotal();
        return new PageResult(total,setMeals);
    }
    //删除套餐
    @Override
    public void deleteById(Integer id) {
        //删除与套餐相关联的检查组（）在套餐检查组关联表
        setMealMapper.deleteCheckGroupAndSetMealById(id);
        //删除套餐
        setMealMapper.deleteSetMealById(id);
        //删除图片
        String filName=setMealMapper.getFileName(id);
        System.out.println(filName);
        deleteFileFromQiniu(filName);
        //静态页面更新
        generateMobileStaticHtml();
    }

    @Override
    public Setmeal findSetMealById(Integer id) {
        Setmeal setmeal= setMealMapper.findSetMealById(id);
        return setmeal;
    }

    @Override
    public List<Integer> selectCheckGroupBySetMealId(Integer id) {
        List<Integer> list =setMealMapper.findCheckGroupsById(id);
        return list;
    }
    //编辑套餐内容
    @Override
    public void update(Setmeal setmeal,Integer [] ids) {
        //修改套餐内容
        setMealMapper.update(setmeal);
        System.out.println(setmeal.toString());
        //修改与检查组的关系
        //删除
        setMealMapper.delete(setmeal.getId());
        //添加
        Map<String,Integer> map=new HashMap<>();
        if(ids!=null && ids.length>0){
            for(Integer checkGroup:ids){
                map.put("checkgroup_id",checkGroup);
                map.put("setmeal_id",setmeal.getId());
                setMealMapper.updateSetMealAndCheckGroup(map);
            }
        }
        //静态页面更新
        generateMobileStaticHtml();
    }

    @Override
    public List<Setmeal> getAllSetmeal() {
        return setMealMapper.getAll();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setMealMapper.findById(id);
    }

    private void addCheckGroups(Integer id, Integer[] checkgroupIds) {
        for(Integer checkGroupId:checkgroupIds){
            Map<String,Integer> map=new HashMap<>();
            map.put("setmeal_id",id);
            map.put("checkgroup_id",checkGroupId);
            setMealMapper.addCheckGroups(map);
        }
    }
}
